package com.itqf.aop;

import com.alibaba.fastjson.JSON;
import com.itqf.entity.SysLog;
import com.itqf.service.SysLogService;
import com.itqf.utils.HttpContextUtils;
import com.itqf.utils.IPUtils;
import com.itqf.utils.ShiroUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2020/11/27
 * @Time: 上午9:26
 */
@Component
@Aspect
public class MyLogAspect {

    @Resource
    private SysLogService sysLogService;

    //@Pointcut("execution(* com.itqf.service.impl.*.*(..))")//被增强方法  service
    @Pointcut("@annotation(com.itqf.aop.MyLog)") //被注解修饰的实例或者方法
    public  void myPointcut(){}

    //后置增强
    @After("myPointcut()")
    public  void after(JoinPoint joinPoint){//如何得到目标方法信息？？？？-->JoinPoint
       // System.out.println("------>被增强了！！！");
        SysLog sysLog = new SysLog();
        String username = ShiroUtils.getCurrentUser().getUsername();
        sysLog.setUsername(username);
        sysLog.setCreateDate(new Date());
        sysLog.setIp(IPUtils.getIpAddr(HttpContextUtils.getHttpServletRequest()));//HttpServletRequest
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        sysLog.setMethod(className+"."+methodName);//目标方法
        String params = JSON.toJSONString(joinPoint.getArgs());//joinPoint.getArgs()
        sysLog.setParams(params);//掉用方法传递的实参
        //操作: @MyLog(value="",description = "批量删除菜单")
        //如何得到目标方法的注解？
        //1.得到目标方法的Method对象
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        //2.然后通过反射去获取注解
        MyLog log =  method.getAnnotation(MyLog.class);
        String operation = null;
        if (log!=null){
            operation = log.description();
        }
        sysLog.setOperation(operation);//用户的操作是什么？


        sysLogService.saveLog(sysLog);
        System.out.println("------>记录日志成功！！"+sysLog);
    }


}
